co = coroutine.create(function () 
	for i = 1, 10 do
		print("co" .. i)
		coroutine.yield()
	end
end)
print(type(co))
print(coroutine.status(co))
coroutine.resume(co)
print(coroutine.status(co))

-- use resume-yield to exchange data
function producer ()
	while true do
		local x = io.read() 	-- generate a new value
		send(x) 							-- send to consumer
	end
end

function consumer ()
	while true do
		local x = receive() 	-- receive the send value
		io.write(x, "\n") 		-- consume
	end
end

function receive ()
	local status, value = coroutine.resume(p)
	return value
end

function send (x)
	coroutine.yield(x)
end
--[[
p= coroutine.create(producer)
c = coroutine.create(consumer)
coroutine.resume(p)
coroutine.resume(c)
--]]

-- coroutine as iterator
function permgen (a, n)
	n = n or #a
	if n <= 1 then
		coroutine.yield(a)
	else
		for i = 1, n do
			a[n], a[i] = a[i], a[n]
			permgen(a, n - 1)
			a[n], a[i] = a[i], a[n]
		end
	end
end

function printResult (a)
	for i = 1, #a do io.write(a[i], " ") end
	io.write("\n")
end

function permutations (a)
	local co = coroutine.create(function () permgen(a) end)
	return function () 	-- iterator function
		local code, res = coroutine.resume(co)
		return res
	end
end

for p in permutations{"a", "b", "c"} do
	printResult(p)
end
